var wxCharts = require('../../utils/wxcharts.js');
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var SDKVersion = '';
var uid = 0;

Page({

  data: {
    util: util,
    screenWidth: 320,
    uid: 0,
    token: '',

    tc: 0,
    hasData: false,
    userInfo: {},

    monthArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    yearArray: [],
    monthIndex: 0,
    yearIndex: 0,

    sellDatas: ''
  },

  mendianId: '',//门店id

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: 'loading',
      mask: 'true'
    });
    var that = this;
    var tc = app.get_tc();
    that.setData({
      tc: tc
    })
    that.mendianId = options.mendianid ? options.mendianid : '';
    var titlename = tc == 1 ? '營銷報表' : '营销报表';
    wx.setNavigationBarTitle({
      title: titlename,
    });

    let date = new Date();
    let year = date.getFullYear();
    let yearArr = [year, year - 1];
    let monthId = date.getMonth();
    wx.getSystemInfo({
      success: function(res) {
        that.screenWidth = res.windowWidth;
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          screenWidth: res.windowWidth,
          isIphone_x: isIphone_x,
          yearArray: yearArr,
          monthIndex: monthId
        });
      }
    })


    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color,
      })
    });

    this.getLoginUserInfo('');

    this.getSellData();
  },

  getLoginUserInfo: function(inviteuid) {
    var that = this;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {
        //更新数据
        uid = res.uid,
          that.setData({
            uid: res.uid,
            token: res.token
          })
      }
    }, inviteuid);
  },

  getSellData: function() {
    // http://admin.jawanology.com/api.php?ac=getGuiMonth&year=2018&month=11&publickey=ZGZvI1mi8Q&binduid=21660
    // 这个接口，传入year和month和binduid，返回数字是1 - 31每天，返回的all字段是整个月的
    var that = this;
    let year = this.data.yearArray[this.data.yearIndex];
    let month = this.data.monthArray[this.data.monthIndex];
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getGuiMonth",
        "mendianid": that.mendianId,
        "year": year,
        "month": month
      },
      success: function(responseData) {
        console.log("销售数据：", responseData.data);
        let data = responseData.data;
        let allIn = (data.all['in'] / 100).toFixed(2);
        let allOut = (data.all.out / 100).toFixed(2);
        let allPt = (allIn - allOut).toFixed(2);
        data.all['in'] = allIn;
        data.all.out = allOut;
        data.all.pt = allPt;
        that.setData({
          sellDatas: responseData.data
        })
        that.setReportForm(year, month);
        wx.hideLoading();
      }
    });
  },

  //下拉选项改变值
  yearChange: function(e) { //选项改变触发事件
    this.setData({
      yearIndex: e.detail.value
    })
  },
  monthChange: function(e) { //选项改变触发事件
    this.setData({
      monthIndex: e.detail.value
    })
    this.getSellData();
  },

  //赋值折线图
  setReportForm: function(year, monthId) {
    // series: [{ // 数据列表
    //   name: '1', // 数据名称
    //   color: '#5AC59F' // 配色，不传入则使用系统默认配色方案
    // }]
    //上半月
    let categoriesData = this.getCategoriesData(1, 15);
    let seriesData_in = this.getSeriesDatas(1, 15, 'in');
    let seriesData_out = this.getSeriesDatas(1, 15, 'out');
    let seriesData_pt = this.getSeriesDatas(1, 15, 'pt');
    let col_w = this.data.screenWidth / 30;
    let column1 = {
      canvasId: 'mReport1', // canvas-id
      type: 'column', // 图表类型，可选值为pie, line, column, area, ring
      categories: categoriesData,
      series: [{ // 数据列表
          name: '销售额', // 数据名称
          data: seriesData_in,
          format: function(val, name) {
            return val.toFixed(2);
          },
        },
        { // 数据列表
          name: '成本', // 数据名称
          data: seriesData_out,
          format: function(val, name) {
            return val.toFixed(2);
          },
          color: '#64f064'
        },
        { // 数据列表
          name: '利润', // 数据名称
          data: seriesData_pt,
          format: function(val, name) {
            return val.toFixed(2);
          },
          color: '#f06464'
        },
      ],
      yAxis: {
        format: function(val) {
          return val.toFixed(0);
        },
        max: 100,
        min: 0
      },
      width: this.data.screenWidth, // 宽度，单位为px
      height: 160, // 高度，单位为px
      legend: true, // 是否显示图表下方各类别的标识
      dataLabel: false, // 是否在图表中显示数据内容值
      extra: {
        column: {
          width: col_w // 柱状图每项的图形宽度，单位为px
        }
      }
    }
    new wxCharts(column1);

    // //下半月
    let end2 = this.getMonthDayLength(year, monthId);
    let categoriesData2 = this.getCategoriesData(16, end2);
    let seriesData_in2 = this.getSeriesDatas(16, end2, 'in');
    let seriesData_out2 = this.getSeriesDatas(16, end2, 'out');
    let seriesData_pt2 = this.getSeriesDatas(16, end2, 'pt');
    let column2 = {
      canvasId: 'mReport2', // canvas-id
      type: 'column', // 图表类型，可选值为pie, line, column, area, ring
      categories: categoriesData2,
      series: [{ // 数据列表
          name: '销售额', // 数据名称
          data: seriesData_in2,
          format: function(val, name) {
            return val.toFixed(2);
          },
        },
        { // 数据列表
          name: '成本', // 数据名称
          data: seriesData_out2,
          format: function(val, name) {
            return val.toFixed(2);
          },
          color: '#64f064'
        },
        { // 数据列表
          name: '利润', // 数据名称
          data: seriesData_pt2,
          format: function(val, name) {
            return val.toFixed(2);
          },
          color: '#f06464'
        },
      ],
      yAxis: {
        format: function(val) {
          return val.toFixed(0);
        },
        max: 100,
        min: 0
      },
      width: this.data.screenWidth, // 宽度，单位为px
      height: 160, // 高度，单位为px
      legend: true, // 是否显示图表下方各类别的标识
      dataLabel: false, // 是否在图表中显示数据内容值
      extra: {
        column: {
          width: col_w // 柱状图每项的图形宽度，单位为px
        }
      }
    }
    new wxCharts(column2);
  },
  getCategoriesData: function(start, end) {
    let categoriesArr = [];
    for (let i = start; i <= end; i++) {
      let name = '' + i;
      categoriesArr.push(name);
    }
    return categoriesArr;
  },

  //type： in：营收   out：成本  pf：利润
  getSeriesDatas: function(start, end, type) {
    let seriesArr = [];
    for (let i = start; i <= end; i++) {
      let key = '' + i;
      let val_in = this.data.sellDatas[key]['in'];
      val_in = val_in ? (val_in / 100).toFixed(1) : 0;
      let val_out = this.data.sellDatas[key]['out'];
      val_out = val_out ? (val_out / 100).toFixed(1) : 0;
      let val = val_in;
      if (type == 'pt') {
        val = (val_in - val_out).toFixed(1);
      } else if (type == 'out') {
        val = val_out;
      }
      let valFloat = parseFloat(val);
      seriesArr.push(valFloat);
    }
    return seriesArr;
  },

  getMonthDayLength: function(year, month) {
    let len = 31;
    if (month == 2) {
      if (year % 4 == 0) {
        len = 29
      } else {
        len = 28
      }
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
      len = 30
    }
    return len;
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;    
    wx.navigateTo({ url: url })
  }

  
})